/*
 * Copyright (C) 2013 Daniel Treffenstädt <daniel@treffenstaedt.de>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301  USA
 */

#include "OLog.h"

#include <QTextStream>
#include <QString>
#include <QDir>

#include <iostream>

#include <cstdlib>

using std::endl;
using std::cout;
using std::cerr;

O_START_NAMESPACE

String				Log::m_fileName;
Log::Type			Log::m_printMessages;
QFile				*Log::m_file;


bool Log::init(String logFile, Type printMessages)
{
	if (logFile.length() > 2)
	{
		if (logFile.charAt(0) == '~' &&logFile.charAt(1) == '/')
		{
			logFile.remove(0, 1);
			cout<<logFile<<endl;
			logFile		= String(QDir::toNativeSeparators(QDir::homePath().append(logFile.c_str())).toStdString());
			cout<<logFile<<endl;
		}
	}
	m_fileName		= logFile;
	m_printMessages	= printMessages;

	m_file	= new QFile(logFile.c_str());

	QFile::OpenModeFlag openMode	= QFile::WriteOnly;

	if (m_file->exists())
	{
		cout<<"Log file exists"<<endl;
		openMode	= QFile::Append;
	}

	if (!m_file->open(openMode))
	{
		delete m_file;
		m_file	= 0;
		cerr<<"Couldn't initialize log."<<endl;
		return false;
	}
	return true;
}

void Log::saveMessage(String msg)
{
	QTextStream str(m_file);

	str<<msg.c_str()<<endl;
}

String Log::toString(Type type)
{
	switch (type)
	{
	case Type::Notice:
		return String("Notice");
		break;
	case Type::Warning:
		return String("Warning");
		break;
	case Type::Error:
		return String("Error");
		break;
	case Type::Message:
	default:
		return String("Message");
		break;
	}
}

void Log::message(String message, int line, String file, Type type)
{
	if (m_file == 0)
	{
		return;
	}

	String msg		= toString(type) + ": " + file + ": " + String::number(line) + ": " + message;

	saveMessage(msg);

	if (type >= m_printMessages)
	{
		if (type != Type::Message)
		{
			cerr<<msg<<endl;
		}
		else
		{
			cout<<message<<endl;
		}

		if (type == Type::Error)
		{
			cerr<<"exiting"<<endl;
			exit(EXIT_FAILURE);
		}
	}
}

void Log::message(String msg)
{
	Log::message(msg, 0, "", Type::Message);
}


O_END_NAMESPACE
